package model

import (
	"gorm.io/gorm"
	"time"
)

type Heart struct {
	gorm.Model
	UserId   uint      `json:"user_id"`
	Heart    int       `json:"heart"`
	TimeDate time.Time `json:"time_date"`
}

func (h *Heart) Create(db *gorm.DB) error {
	return db.Create(h).Error
}

func (h *Heart) Get(db gorm.DB) error {
	return db.First(h).Error
}

func (h *Heart) GetBefore(db *gorm.DB, before Time) error {
	return db.Where(Eq("user_id", h.UserId)).Where(LtEq("time_date", before.Time)).Order("time_date desc").Find(h).Error
}

func (h *Heart) Updates(db *gorm.DB) error {
	return db.Updates(h).Error
}

type HeartSelectConditions struct {
	Start Time `json:"start"`
	End   Time `json:"end"`
}

func ListHearts(db *gorm.DB, where map[string]any, conditions *HeartSelectConditions) []Heart {
	var hearts []Heart
	sql := db.Table("hearts").Where(where)

	if conditions.Start.Time.Unix() > 0 {
		sql = sql.Where(GtEq("time_date", conditions.Start.Time))
	}
	if conditions.End.Time.Unix() > 0 {
		sql = sql.Where(LtEq("time_date", conditions.End.Time))
	}
	sql.Find(&hearts)
	return hearts
}
